class Subject {
    constructor() {
        this.observers = []
    }
    attach (observer) {
        this.observers.push(observer)
    }
    detach (observer) {
        const index = this.observers.indexOf(observer)
        if (index > -1) {
            this.observers.splice(index, 1)
        }
    }
    notify () {
        for (const observer of this.observers) {
            observer.update(this)
        }
    }
}

class Observer {
    update (subject) { }
}

class ConcreteSubject extends Subject {
    constructor(state) {
        super()
        this.state = state
    }
    set_state (state) {
        this.state = state
        this.notify()
    }
    get_state () {
        return this.state
    }
}

class ConcreteObserver extends Observer {
    update (subject) {
        console.log(this, `更新了值: ${subject.get_state()}`)
    }
}

let subject = new ConcreteSubject('initial state')
let observer = new ConcreteObserver()

subject.attach(observer)
subject.set_state('new state')